<template>
  <div>
    <CategorySelector :disabled="!isShowList" />
    <div v-show="isShowList">
      <el-card class="attr-card">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="isShowList = false"
        >
          添加属性
        </el-button>
        <el-table
          class="attr-table"
          :data="attrs"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
          ></el-table-column>
          <el-table-column prop="attrName" label="属性名称"></el-table-column>
          <el-table-column label="属性值列表">
            <template v-slot="{ row }">
              <el-tag
                class="attr-tag"
                v-for="valueName in row.attrValueList"
                :key="valueName.id"
                >{{ valueName.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-edit"
                @click="showUpdateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="delAttr(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div v-show="!isShowList">
      <el-form inline :rules="rules" :model="attr">
        <el-form-item label="属性名" prop="attrName">
          <el-input type="text" v-model="attr.attrName"></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        icon="el-icon-plus"
        :disabled="!attr.attrName"
        @click="showAddAttrValue"
      >
        添加属性值
      </el-button>
      <el-table
        class="attr-table"
        :data="attrValueList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column label="属性值名称">
          <template v-slot="{ row, $index }">
            <el-input
              placeholder="请输入属性值名称"
              :ref="$index"
              size="mini"
              v-model="attr.valueName"
              @blur="addAttrValue(row)"
              @keyup.enter="addAttrValue(row)"
              v-show="row.isEdit"
            ></el-input>
            <span
              style="display: block"
              @click="toEdit(row, $index)"
              v-show="!row.isEdit"
            >
              {{ row.valueName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-popconfirm
              @onConfirm="delAttrValue($index)"
              :title="`确定要删除 ${
                row.valueName ? row.valueName : '空'
              } 属性值吗？`"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                slot="reference"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addAttr">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { reqGetAttrList, reqAddAttrInfo, reqDelAttr } from "@api/attr";

export default {
  name: "Attr",
  data() {
    return {
      attrs: [],
      attrValueList: [],
      loading: false,
      isShowList: true,
      isEdit: false,
      attr: {
        attrName: "",
        valueName: "",
      },
      rules: {
        attrName: [
          { require: true, message: "请输入属性名称", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      category1Id: (state) => state.category.category1Id,
      category2Id: (state) => state.category.category2Id,
      category3Id: (state) => state.category.category3Id,
    }),
  },
  watch: {
    async category3Id() {
      try {
        const { category1Id, category2Id, category3Id } = this;

        // 如果 category3Id 没有， 不请求数据
        if (!category3Id) {
          this.attrs = [];
          return;
        }
        const res = await reqGetAttrList({
          category1Id,
          category2Id,
          category3Id,
        });

        this.attrs = res.data;
      } catch {
        this.$message.error("请求属性列表数据失败~");
      }
    },
  },
  methods: {
    showUpdateAttr(row) {
      this.isShowList = false;
      this.attr.attrName = row.attrName;
      this.attr.id = row.id;
      this.attrValueList = row.attrValueList
    },
    delAttr(attr) {
      this.$confirm(
        `您确认要删除 <b style="color: red;">${attr.attrName}</b> 品牌数据吗?`,
        "提示",
        {
          dangerouslyUseHTMLString: true, // 让内部代码解析成html
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        this.loading = true;
        await reqDelAttr(attr.id);
        this.$message({
          type: "success",
          message: "删除属性数据成功",
        });
        const { category1Id, category2Id, category3Id } = this;

        const res = await reqGetAttrList({
          category1Id,
          category2Id,
          category3Id,
        });

        this.attrs = res.data;
        this.loading = false;
      });
    },
    async addAttr() {
      const { attrName, id } = this.attr;
      if (!attrName) {
        this.$message.warning("请输入属性名");
        return;
      }
      const { attrValueList, isEdit } = this;
      if (isEdit) {
        return;
      }
      if (attrValueList.length === 0) {
        this.$message.warning("请添加至少一个属性值");
        return;
      }
      const { category1Id, category2Id, category3Id } = this;
      const data = {
        attrName,
        attrValueList: attrValueList.map((attr) => {
          return {
            valueName: attr.valueName,
          };
        }),
        categoryId: category3Id,
        categoryLevel: 3,
      };
      if (id) {
        data.id = id;
      }
      try {
        await reqAddAttrInfo(data);
        this.$message.success(`${id ? "更新" : "添加"}属性成功`);
        const res = await reqGetAttrList({
          category1Id,
          category2Id,
          category3Id,
        });
        this.attrs = res.data;
        this.cancel();
      } catch (e) {
        console.log(e);
        this.$message.error("添加属性失败");
      }
    },
    cancel() {
      this.isShowList = true;
      this.attrValueList = [];
      this.attr = {
        attrName: "",
        valueName: "",
      };
    },
    toEdit(row, index) {
      if (this.isEdit) return;
      row.isEdit = true;
      this.isEdit = true;
      this.attr.valueName = row.valueName;
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    addAttrValue(row) {
      const { valueName } = this.attr;
      if (!valueName) {
        this.$message.warning("请输入属性值");
        return;
      }
      row.valueName = valueName;
      const repeatCount = this.attrValueList.reduce((p, c) => {
        return p + (c.valueName === valueName ? 1 : 0);
      }, 0);
      if (repeatCount > 1) {
        this.$message.warning("输入属性值重复");
        return;
      }
      this.attr.valueName = "";
      row.isEdit = false;
      this.isEdit = false;
    },
    showAddAttrValue() {
      if (this.isEdit) return;
      const length = this.attrValueList.push({ isEdit: true });
      this.isEdit = true;
      this.$nextTick(() => {
        this.$refs[length - 1].focus();
      });
    },
    delAttrValue(index) {
      this.attrValueList.splice(index, 1);
    },
  },
};
</script>

<style lang="sass" scoped>
.attr-card
  margin: 8px
.attr-table
  margin-top: 16px
.attr-tag
  margin-right: 8px
  margin-bottom: 8px
</style>
